package io.dshubs.archives.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import io.dshubs.archives.dao.ArchiveBaseRuleMapper;
import io.dshubs.archives.entity.ArchiveBaseInfo;
import io.dshubs.archives.dao.ArchiveBaseInfoMapper;
import io.dshubs.archives.entity.ArchiveBaseRule;
import io.dshubs.archives.service.ArchiveBaseInfoService;
import io.dshubs.archives.service.ArchiveBaseRuleService;
import io.dshubs.commons.mybatis.enums.DelFlagEnum;
import io.dshubs.commons.mybatis.service.impl.BaseServiceImpl;
import io.dshubs.commons.security.user.SecurityUser;
import io.dshubs.commons.security.user.UserDetail;
import io.dshubs.commons.tools.constant.Constant;
import io.dshubs.commons.tools.enums.SuperAdminEnum;
import io.dshubs.commons.tools.exception.RenException;
import io.dshubs.commons.tools.page.PageData;
import io.dshubs.commons.tools.utils.Result;
import io.dshubs.dto.SysTenantDTO;
import io.dshubs.feign.TenantFeignClient;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 全宗信息表 服务实现类
 * </p>
 *
 * @author tan
 * @since 2021-08-16
 */
@Service
public class ArchiveBaseInfoServiceImpl extends BaseServiceImpl<ArchiveBaseInfoMapper, ArchiveBaseInfo> implements ArchiveBaseInfoService {

    @Autowired
    private TenantFeignClient tenantFeignClient;

    @Autowired
    private ArchiveBaseRuleMapper archiveBaseRuleMapper;

    @Autowired
    private ArchiveBaseRuleService archiveBaseRuleService;

    @Override
    public PageData<ArchiveBaseInfo> page(Map<String, Object> params) {
        IPage<ArchiveBaseInfo> page = baseDao.selectPage(
                getPage(params, Constant.CREATE_DATE, false),
                getWrapper(params)
        );
        if(page.getTotal() > 0) {
            page.getRecords().forEach(i->{
                Result<SysTenantDTO> result = tenantFeignClient.getTenantByCode(i.getTenantCode());
                i.setTenantName(result.getData() == null ? "":result.getData().getTenantName());
            });
        }
        return getPageData(page, ArchiveBaseInfo.class);
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public void save(ArchiveBaseInfo archiveBaseInfo) {
        Long tenantCode = archiveBaseInfo.getTenantCode();
        if(null == tenantCode) {
            tenantCode = SecurityUser.getTenantCode();
        }
        List<ArchiveBaseInfo> archiveBaseInfoList = this.baseDao.selectList(new QueryWrapper<ArchiveBaseInfo>().eq("tenant_code", tenantCode));
        if(archiveBaseInfoList.size() > 0) {
            throw new RenException("该组织已经存在全宗，请走修改，或先删除");
        }
        this.baseDao.insert(archiveBaseInfo);
        if(StringUtils.isNotEmpty(archiveBaseInfo.getRuleArchiveId())) {
            List<ArchiveBaseRule> archiveBaseRuleList = archiveBaseRuleMapper.selectList(new QueryWrapper<ArchiveBaseRule>().eq("archive_id",
                    archiveBaseInfo.getRuleArchiveId()));
            if(CollectionUtils.isNotEmpty(archiveBaseRuleList)) {
                archiveBaseRuleList.forEach(item->{
                    item.setArchiveId(archiveBaseInfo.getId());
                    item.setId(null);
                    item.setCreateDate(new Date());
                });
                archiveBaseRuleService.insertBatch(archiveBaseRuleList);
            }
        }
    }

    private QueryWrapper<ArchiveBaseInfo> getWrapper(Map<String, Object> params){
        String name = (String)params.get("name");
        String tenantCode = (String)params.get("tenantCode");
        QueryWrapper<ArchiveBaseInfo> wrapper = new QueryWrapper<>();
        wrapper.eq(Constant.DEL_FLAG, DelFlagEnum.NORMAL.value());
        wrapper.like(StringUtils.isNotBlank(name), "name", name);
        wrapper.eq(StringUtils.isNotBlank(tenantCode),"tenant_code",tenantCode);
        UserDetail user = SecurityUser.getUser();
        if(StringUtils.isEmpty(tenantCode) && user.getSuperAdmin() != SuperAdminEnum.YES.value()) {
            wrapper.eq("tenant_code",user.getTenantCode());
        }
        return wrapper;
    }

    @Override
    public List<ArchiveBaseInfo> list(Map<String, Object> params) {
        return baseDao.selectList(getWrapper(params));
    }
}
